package com.example.treehole.fragmnet;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.treehole.R;
import com.example.treehole.activity.DynamicDetailActivity;
import com.example.treehole.adapter.DynamicMyAdapter;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.DynamicResponse;
import com.example.treehole.entity.MyCountResponse;
import com.example.treehole.utils.ConvertEntityUtils;
import com.example.treehole.viewobject.DynamicOutSide;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;


public class MyTreeHoleFragment extends BaseFragment {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.sh_is_pri)
    Switch shIsPri;
    @BindView(R.id.tv_count)
    TextView tvCount;

    List<DynamicOutSide> data = new ArrayList<>();
    DynamicMyAdapter adapter;
    int pageNum = 1;
    int countAll = 0;
    int countApart = 0;
    int position=0;

    public static MyTreeHoleFragment newInstance() {
        return new MyTreeHoleFragment();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                adapter.setData(data);
                adapter.notifyDataSetChanged();
            } else if (msg.what == 2) {
                String str="一共";
                if (!shIsPri.isChecked())
                    str+=countAll;
                else
                    str+=countApart;
                str+="条动态";
                tvCount.setText(str);
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.fragment_my_tree_hole;
    }

    @Override
    protected void initData(View view) {
        adapter = new DynamicMyAdapter(getActivity());
        adapter.setOnMyItemClickListener(new DynamicMyAdapter.OnItemClickListener() {
            @Override
            public void onClick(int pos) {
                Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("id", data.get(pos).getId());
                intent.putExtra("isMine", true);
                position=pos;
                startActivityForResult(intent,200);
            }
            @Override
            public void onCLickLong(int pos) {

            }
        });
        loadCount();
        loadData(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                loadData(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData(false);
            }
        });
        shIsPri.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum=1;
                mHandler.sendEmptyMessage(2);
                loadData(true);
            }
        });
    }

    private void loadCount() {
        String id = getStringFromSp("id");
        Api.config(ApiConfig.GET_DYNAMIC_COUNT + "?userId=" + id, new HashMap<>()).getRequest(requireContext(), new Callback() {
            @Override
            public void onSuccess(String res) {
                MyCountResponse response = new Gson().fromJson(res, MyCountResponse.class);
                if (response.getCode().equals("200")) {
                    countAll = response.getData().getCount();
                    countApart = response.getData().getAnonymity();
                    mHandler.sendEmptyMessage(2);
                } else {
                    showToastSync(response.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    private void loadData(boolean isRefresh) {
        int index = shIsPri.isChecked() ? 1 : -1;
        String url = ApiConfig.GET_DYNAMIC_MY;
        HashMap<String, String> map = new HashMap<>();
        String id = getStringFromSp("id");
        map.put("userId", id);
        map.put("page", String.valueOf(pageNum));
        map.put("index", String.valueOf(index));
        Api.config(url, map).postRequest(requireContext(), new Callback() {
            @Override
            public void onSuccess(String res) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
                DynamicResponse dynamicResponse = new Gson().fromJson(res, DynamicResponse.class);
                String code = dynamicResponse.getCode();
                if (code.equals("200")) {
                    List<DynamicResponse.DataDTO> dataDTOS = dynamicResponse.getData();
                    List<DynamicOutSide> newData = new ArrayList<>();
                    if (dataDTOS != null)
                        newData = ConvertEntityUtils.convertToDynamicOutSideForOnly(dataDTOS);
                    if (isRefresh) {
                        data = newData;
                    } else {
                        if (newData.size() == 0)
                            showToastSync(getString(R.string.no_more_data));
                        data.addAll(newData);
                    }
                    mHandler.sendEmptyMessage(1);
                } else {
                    showToastSync(dynamicResponse.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            this.data.remove(position);
            adapter.notifyItemRemoved(position);
            adapter.notifyItemRangeChanged(position, this.data.size() - position);
        }
    }
}